import { ClientMessage } from "@runtime/generate/message/ClientMessage";
import WebSocketComponent from "@runtime/module/WebSocket/WebSocketComponent";
import { ref, Ref, UnwrapNestedRefs } from "vue";

/**
 * 资源加载组件
 */
export default class AssetLoaderComponent {
    private static instance: AssetLoaderComponent = new AssetLoaderComponent();
    /**
     * 资源加载组件
     */
    public static get Default(): AssetLoaderComponent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);
    }

    public Progress: Ref<number> = ref(0);

    /**
     * 加载资源
     * @param asset 资源
     * @returns 实例化Id
     */
    public async LoadAsync(asset: string): Promise<number> {
        const response: ClientMessage.LoadAssetResponse = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.LoadAssetRequest(asset));
        return response.InstanceId;
    }

    /**
     * 加载资源
     * @param assets 资源
     * @returns 实例化Id
     */
    public async LoadAllAsync(assets: Array<string>): Promise<Array<number>> {
        this.Progress.value = 0;
        const response: ClientMessage.LoadAllAssetResponse = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.LoadAllAssetRequest(assets));
        this.Progress.value = 100;
        return response.InstanceIds;
    }
}